package org.yhhhhhhh.ai_jianli.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.yhhhhhhh.ai_jianli.model.Role;
import org.yhhhhhhh.ai_jianli.model.User;
import org.yhhhhhhh.ai_jianli.repository.RoleRepository;
import org.yhhhhhhh.ai_jianli.repository.UserRepository;

import java.util.HashSet;
import java.util.Set;

@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        // 创建角色
        if (roleRepository.findByName("ROLE_ADMIN").isEmpty()) {
            Role adminRole = new Role();
            adminRole.setName("ROLE_ADMIN");
            roleRepository.save(adminRole);
        }

        if (roleRepository.findByName("ROLE_USER").isEmpty()) {
            Role userRole = new Role();
            userRole.setName("ROLE_USER");
            roleRepository.save(userRole);
        }

        // 创建管理员用户
        if (userRepository.findByUsername("admin").isEmpty()) {
            User admin = new User();
            admin.setUsername("admin");
            admin.setEmail("admin@example.com");
            admin.setPassword(passwordEncoder.encode("admin123"));

            Set<Role> roles = new HashSet<>();
            // 替换 orElse(null) 为 orElseThrow，确保角色必须存在
            roles.add(roleRepository.findByName("ROLE_ADMIN")
                    .orElseThrow(() -> new IllegalStateException("ROLE_ADMIN 角色未找到，请检查角色创建逻辑")));
            roles.add(roleRepository.findByName("ROLE_USER")
                    .orElseThrow(() -> new IllegalStateException("ROLE_USER 角色未找到，请检查角色创建逻辑")));
            admin.setRoles(roles);

            userRepository.save(admin);
            System.out.println("管理员账户已创建: 用户名=admin, 密码=admin123");
        }
    }
}
